package com.duoec.dw.lineage.service.analyser.expr;

import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.duoec.dw.lineage.exceptions.FieldNotFoundLineageAnalyserException;
import com.duoec.dw.lineage.core.utils.AnalyserUtils;
import com.duoec.dw.lineage.dto.MultiTableLineageDto;
import com.duoec.dw.lineage.dto.TableFieldDependencyDto;
import com.duoec.dw.lineage.dto.TableFieldLineageDto;
import com.duoec.dw.lineage.dto.TableLineageDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.LinkedHashSet;

/**
 * @author xuwenzhen
 */
@Service
public class IdentifierExprAnalyser extends BaseExprAnalyser<SQLIdentifierExpr> {
    private static final Logger logger = LoggerFactory.getLogger(IdentifierExprAnalyser.class);

    /**
     * 获取匹配类型
     *
     * @return 类型
     */
    @Override
    public Class<SQLIdentifierExpr> getSqlExprType() {
        return SQLIdentifierExpr.class;
    }

    /**
     * 分析表达式语句
     *
     * @param expr         表达式语句
     * @param fromLineages 当前语句from解析出来的血缘关系
     * @return 此表达式抽取出来的依赖
     */
    @Override
    public LinkedHashSet<TableFieldDependencyDto> analyse(SQLIdentifierExpr expr, MultiTableLineageDto fromLineages) {
        String fieldName = AnalyserUtils.formatFieldName(expr.getName());
        if (fromLineages.size() == 1) {
            TableLineageDto table = fromLineages.getFirst();
            TableFieldLineageDto field = table.getField(fieldName);
            return getDependencies(table, field, fieldName);
        }
        return fromLineages.searchByFieldName(fieldName, (table, field) -> {
            if (table == null) {
                throw new FieldNotFoundLineageAnalyserException("无法定位字段:" + fieldName + ",在哪个表上:" + fromLineages.keysToString());
            } else {
                return getDependencies(table, field, fieldName);
            }
        });
    }
}
